package com.shijunhao.graduation.config;

import com.shijunhao.graduation.properties.WebSecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author: shijunhao
 * @date: 2022/3/2 14:27
 * @description: springSecurity管理配置
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsService userDetailsServiceImpl;
    private final PasswordEncoder passwordEncoder;
    private final WebSecurityProperties properties;

    @Autowired
    public WebSecurityConfig(@Qualifier("userDetailServiceImpl") UserDetailsService userDetailsServiceImpl, PasswordEncoder passwordEncoder, WebSecurityProperties properties) {
        this.userDetailsServiceImpl = userDetailsServiceImpl;
        this.passwordEncoder = passwordEncoder;
        this.properties = properties;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //允许swagger与静态资源文件，而无需认证
                .antMatchers(properties.permitUrls).permitAll()
                //剩余所有请求都需要验证
                .antMatchers("/**").authenticated()
                .and()
                //配置登录相关操作
                .formLogin().loginProcessingUrl(properties.loginUrl)
                .usernameParameter(properties.username).passwordParameter(properties.password)
                .successHandler(properties.authSuccessHandler).failureHandler(properties.authenticationFailureHandler)
                .and()
                //配置登出相关操作
                .logout().logoutUrl(properties.logoutUrl).logoutSuccessHandler(properties.logoutSuccessHandler)
                .and()
                //post请求要关闭csrf验证,不然访问报错；
                .csrf().disable();
    }
}
